package com.zbh.uexam.listener;

import com.zbh.uexam.configuration.application.ApplicationContextProvider;
import com.zbh.uexam.configuration.spring.security.UserSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @Author zhoubh
 * @Date 2021/3/23 13:36
 * @Version 1.0
 * @description: session登陆监听
 */
@WebListener
@Configuration
public class HttpSessionLoginListener implements HttpSessionListener {

    private final Logger logger = LoggerFactory.getLogger(HttpSessionLoginListener.class);

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        logger.info("监听创建");
        //监听到HttpSession被创建时，就把当前HttpSession对象存储在SessionMap中
        HttpSession session = httpSessionEvent.getSession();
        UserSessionManager userSessionManager =
                ApplicationContextProvider.getBean(UserSessionManager.class);
        logger.info("添加sessionId:{}, session:{}",session.getId(), session);
        userSessionManager.putSessionMap(session.getId(), session);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        logger.info("监听销毁");
        //当有HttpSession对象被销毁时就删除UserSessionMap中的键值对
        String sessionId = httpSessionEvent.getSession().getId();
        UserSessionManager userSessionManager =
                ApplicationContextProvider.getBean(UserSessionManager.class);
        logger.info("删除sessionId:{}, session:{}",sessionId, httpSessionEvent.getSession());
        userSessionManager.removeInUserSessionMap(sessionId);
    }
}
